package com.shd.edanpei.view.addressPicker;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.shd.edanpei.R;
import com.shd.edanpei.base.BaseQuickImageAdapter;
import com.shd.edanpei.base.dialog.DialogUtil;
import com.shd.edanpei.util.ToastUtil;
import com.shd.edanpei.view.picker.AddressBean;
import com.socks.library.KLog;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mc on 2018/10/16.
 * yang-wen-wen
 */

public class MultipleAddressPicker extends RelativeLayout {

    private Context mContext;

    private View cancel, sure;
    private RecyclerView rlv_province, rlv_city, rlv_area;
    private MulitpleAdapter adapterProvince;
    private MulitpleAdapter1 adapterCity;
    private MulitpleAdapter2 adapterArea;

    private StringBuffer jsonSB;
    private AddressBean addressBean;
    private List<AddressBean.AddressItemBean> provinceList = new ArrayList<>();
    private List<AddressBean.AddressItemBean> cityList = new ArrayList<>();
    private List<AddressBean.AddressItemBean> areaList = new ArrayList<>();

    private AddressBean.AddressItemBean mSelectProvice; //选中 省份 bean
    private AddressBean.AddressItemBean mSelectCity;//选中 城市  bean
    private AddressBean.AddressItemBean mSelectDistrict;//选中 区县  bean
    private int mSelectProvicePosition = 0; //选中 省份 位置
    private int mSelectCityPosition = 0;//选中 城市  位置
    private int mSelectDistrictPosition = 0;//选中 区县  位置

    private int mSelectAreaCount = 0;//选中区域数量

    private String areaDesc = "";

    public MultipleAddressPicker(Context context) {
        super(context);
        init(context);
    }

    public MultipleAddressPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MultipleAddressPicker(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    private void init(Context context) {
        this.mContext = context;
        inflate(mContext, R.layout.mulitple_address_picker, this);
        cancel = findViewById(R.id.cancel);
        sure = findViewById(R.id.sure);

        rlv_province = findViewById(R.id.rlv_province);
        rlv_city = findViewById(R.id.rlv_city);
        rlv_area = findViewById(R.id.rlv_area);

        rlv_province.setLayoutManager(new LinearLayoutManager(mContext));
        rlv_city.setLayoutManager(new LinearLayoutManager(mContext));
        rlv_area.setLayoutManager(new LinearLayoutManager(mContext));

        adapterProvince = new MulitpleAdapter(mContext);
        adapterCity = new MulitpleAdapter1(mContext);
        adapterArea = new MulitpleAdapter2(mContext);

        rlv_province.setAdapter(adapterProvince);
        rlv_city.setAdapter(adapterCity);
        rlv_area.setAdapter(adapterArea);

        initData();
        initListener();

    }


    /**
     * 初始化数据
     * 读取assets下的json文件
     */
    private void initData() {
        if (jsonSB == null) {
            jsonSB = new StringBuffer();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
                        mContext.getAssets().open("address.json")));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    jsonSB.append(line);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (addressBean == null) {
            addressBean = new Gson().fromJson(jsonSB.toString(), AddressBean.class);
        }

        if (addressBean != null) {
            //省
            provinceList.clear();
            addressBean.getProvince().get(0).setCheck(true);//默认选中第一个省
            mSelectProvice = addressBean.getProvince().get(0);
            provinceList.addAll(addressBean.getProvince());
            //市
            cityList.clear();
            for (AddressBean.AddressItemBean itemBean : addressBean.getCity()) {
                if (itemBean.getP().equals(mSelectProvice.getI())) {
                    cityList.add(itemBean);
                }
            }
            cityList.get(0).setCheck(true);//默认选中第一个市
            mSelectCity = cityList.get(0);
            //区
            areaList.clear();
            for (AddressBean.AddressItemBean itemBean : addressBean.getDistrict()) {
                if (itemBean.getP().equals(mSelectCity.getI())) {
                    areaList.add(itemBean);
                }
            }
            adapterProvince.setNewData(provinceList);
            adapterCity.setNewData(cityList);
            adapterArea.setNewData(areaList);
        }
    }


    private void initListener() {
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.cancel();
                }
            }
        });
        sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectProvice == null) {
                    ToastUtil.showToast("请先选择省");
                    return;
                }
                if (mSelectCity == null) {
                    ToastUtil.showToast("请先选择市");
                    return;
                }
                if (mSelectAreaCount < 1) {
                    ToastUtil.showToast("请先选择区域");
                    return;
                }
                List<String> areaCode = new ArrayList<>();
                StringBuffer areaDesc = new StringBuffer();
                areaDesc.append(mSelectProvice.getN());
                areaDesc.append(" ");
                areaDesc.append(mSelectCity.getN());
                areaDesc.append(" ");

                for (AddressBean.AddressItemBean itemBean : adapterArea.getData()) {
                    if (itemBean.isCheck()) {
                        areaCode.add(itemBean.getI());
                        areaDesc.append(itemBean.getN());
                        areaDesc.append(";");
                    }
                }
                mListener.sure(areaDesc.toString(), areaCode);
//                ToastUtil.showToast(areaDesc.toString()+"--"+new Gson().toJson(areaCode));
            }
        });
        adapterProvince.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener()

        {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //点击省
                if (mSelectProvicePosition != position) {
                    //修改默认选中的省
                    mSelectProvice = adapterProvince.getItem(position);
                    adapterProvince.getItem(position).setCheck(true);
                    //移除上一个选中省的样式
                    adapterProvince.getItem(mSelectProvicePosition).setCheck(false);
                    adapterProvince.notifyDataSetChanged();
                    mSelectProvicePosition = position;

                    //更新市数据
                    cityList.clear();
                    for (AddressBean.AddressItemBean itemBean : addressBean.getCity()) {
                        if (itemBean.getP().equals(mSelectProvice.getI())) {
                            //默认为未点击样式
                            itemBean.setCheck(false);
                            cityList.add(itemBean);
                        }
                    }
                    //修改默认选中的市
                    mSelectCity = cityList.get(0);
                    mSelectCityPosition = 0;
                    //默认选中第一条
                    cityList.get(0).setCheck(true);
                    adapterCity.setNewData(cityList);

                    //区
                    mSelectAreaCount = 0;
                    areaList.clear();
                    for (AddressBean.AddressItemBean itemBean : addressBean.getDistrict()) {
                        if (itemBean.getP().equals(mSelectCity.getI())) {
                            //默认为未点击样式
                            itemBean.setCheck(false);
                            areaList.add(itemBean);
                        }
                    }
                    adapterArea.setNewData(areaList);
                }
            }
        });
        adapterCity.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener()

        {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mSelectCityPosition != position) {
                    mSelectCity = adapterCity.getItem(position);
                    adapterCity.getItem(position).setCheck(true);
                    adapterCity.getItem(mSelectCityPosition).setCheck(false);
                    adapterCity.notifyDataSetChanged();
                    mSelectCityPosition = position;

                    //区
                    mSelectAreaCount = 0;
                    areaList.clear();
                    for (AddressBean.AddressItemBean itemBean : addressBean.getDistrict()) {
                        if (itemBean.getP().equals(mSelectCity.getI())) {
                            //默认为未点击样式
                            itemBean.setCheck(false);
                            areaList.add(itemBean);
                        }
                    }
                    adapterArea.setNewData(areaList);
                }

            }
        });
        adapterArea.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener()

        {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (adapterArea.getItem(position).isCheck()) {
                    adapterArea.getItem(position).setCheck(false);
                    mSelectAreaCount--;

                } else {
                    adapterArea.getItem(position).setCheck(true);
                    mSelectAreaCount++;
                }
                adapterArea.notifyDataSetChanged();
            }
        });
    }


    private class MulitpleAdapter extends BaseQuickImageAdapter<AddressBean.AddressItemBean> {


        MulitpleAdapter(Context context) {
            super(context, R.layout.item_multiple_address);
        }

        @Override
        protected void convert(BaseViewHolder helper, AddressBean.AddressItemBean item) {
            helper.setText(R.id.text, item.getN());
            if (item.isCheck()) {
                helper.setTextColor(R.id.text, getResources().getColor(R.color.main_color));
            } else {
                helper.setTextColor(R.id.text, getResources().getColor(R.color.black));
            }
        }

    }


    private class MulitpleAdapter1 extends BaseQuickImageAdapter<AddressBean.AddressItemBean> {

        private int position;

        MulitpleAdapter1(Context context) {
            super(context, R.layout.item_multiple_address);
        }

        @Override
        protected void convert(BaseViewHolder helper, AddressBean.AddressItemBean item) {
            position = helper.getLayoutPosition();
            helper.setText(R.id.text, item.getN());
            if (item.isCheck()) {
                helper.setTextColor(R.id.text, getResources().getColor(R.color.main_color));
            } else {
                helper.setTextColor(R.id.text, getResources().getColor(R.color.black));
            }
        }

    }


    private class MulitpleAdapter2 extends BaseQuickImageAdapter<AddressBean.AddressItemBean> {

        private int position;

        MulitpleAdapter2(Context context) {
            super(context, R.layout.item_multiple_address2);
        }

        @Override
        protected void convert(BaseViewHolder helper, AddressBean.AddressItemBean item) {
            position = helper.getLayoutPosition();
            helper.setText(R.id.text, item.getN());
            if (item.isCheck()) {
                helper.setTextColor(R.id.text, getResources().getColor(R.color.main_color));
                ((ImageView) helper.getView(R.id.img)).setImageResource(R.drawable.ic_choose);
            } else {
                helper.setTextColor(R.id.text, getResources().getColor(R.color.black));
                ((ImageView) helper.getView(R.id.img)).setImageResource(R.drawable.ic_unchoose);
            }
        }
    }

    private Listener mListener;

    public interface Listener {

        void cancel();

        void sure(String desc, List<String> code);

    }

    public void setListener(Listener listener) {
        this.mListener = listener;
    }
}
